#!/usr/bin/env python
# lid-manage.py vi:ts=4:sw=4:expandtab:
#
# A tool for managing SSH keys stored in LDAP
# LDAP Information Distribution Suite
#
# Authors:
#       Will Barton <wbb4@opendarwin.org>
#       Landon Fuller <landonf@threerings.net>
#
# Copyright (c) 2005 Three Rings Design, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright owner nor the names of contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import sys, logging, getopt
import ZConfig

import ldap

import lids
from lids import ldaputils, daemon, plugin

def usage():
    print "%s: [-hXZ] [-f config file] [-D binddn] [-lr service]" % sys.argv[0]
    print "    -h           Print usage (this message)"
    print "    -X           Use GSSAPI instead of simple authentication"
    print "    -Z           Issue StartTLS extended operation"
    print "    -D <dn>      Bind with distinguished name"
    print "    -f <config>  Use configuration file"
    print "    -l <service> List matching entries for the specified service"
    print "    -r <service> Run the helper for the specified service once"

def run(conn, config, service):
    options = {}

    if (service.searchbase == None):
        basedn = config.LDAP.basedn
    else:
        basedn = service.searchbase

    for opt in service.Option:
        options[opt.getSectionName()] = opt.value

    try:
        hc = plugin.HelperController(service.getSectionName(), service.helper, service.frequency, basedn,
                service.searchfilter, service.requiregroup, options)

        # Find all per-service groups, if any
        for group in service.Group:

            # Use the default basedn if necessary
            if (group.searchbase == None):
                basedn = config.LDAP.basedn
            else:
                basedn = group.searchbase

            # Instantiate our group filter
            if (group.memberattribute):
                groupFilter = ldaputils.GroupFilter(basedn, ldap.SCOPE_SUBTREE, group.searchfilter, group.memberattribute)
            else:
                groupFilter = ldaputils.GroupFilter(basedn, ldap.SCOPE_SUBTREE, group.searchfilter)

            # Load group-specific helper options
            groupOptions = {}
            groupOptions.update(options)

            for opt in group.Option:
                groupOptions[opt.getSectionName()] = opt.value

            # Add our newly minted group to the controller
            hc.addGroup(groupFilter, groupOptions)

    except plugin.LIDSPluginError, e:
        print "Error initializing service '%s': %s" % (service.getSectionName(), e)
        return

    ctx = daemon.Context(conn)
    ctx.addHelper(hc)
    ctx.run()

def list(conn, config, service):
    if (service.searchbase == None):
        basedn = config.LDAP.basedn
    else:
        basedn = service.searchbase

    res = conn.search(basedn, ldap.SCOPE_SUBTREE, service.searchfilter)
    for entry in res:
        print entry.dn

def main():
    action = None
    serviceName = None
    bindDN = None
    conf_file = None
    simple_bind = True
    modlist = []

    try:
        opts,args = getopt.getopt(sys.argv[1:], "hXZD:f:l:r:")
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    for opt,arg in opts:
        if opt == "-h":
            usage()
            sys.exit()
        if opt == "-X":
            simple_bind = False
        if opt == "-D":
            bindDN = arg
        if opt == "-f":
            conf_file = arg
        if opt == "-l": 
            action = "list"
            serviceName = arg
        if opt == "-r":
            action = "run"
            serviceName = arg

    if (conf_file == None or serviceName == None):
        usage()
        sys.exit(1)

    # Load our configuration schema
    schema = ZConfig.loadSchema(lids.CONFIG_SCHEMA)
    try:
        config, handler = ZConfig.loadConfig(schema, conf_file)
    except ZConfig.ConfigurationError, e:
        print "Configuration Error: %s" % e
        sys.exit(1)

    # Set up logging
    try:
        config.Logging()
    except Exception, e:
        print "Log initialization failed: %s" % e
        sys.exit(1)

    logger = logging.getLogger(lids.LOG_NAME)
    # Add console logging
    console = logging.StreamHandler()
    formatter = logging.Formatter('%(asctime)s %(levelname)-6s %(message)s',
            '%Y%m%d %H:%M:%S')
    console.setLevel(logging.INFO)
    console.setFormatter(formatter)
    console.setLevel(logging.INFO)
    logger.addHandler(console)

    # Find the specified service
    for service in config.Service:
        if (service.getSectionName() == serviceName.lower()):
            break

    if (service.getSectionName() != serviceName.lower()):
        print "No such service: %s" % serviceName
        sys.exit(1)

    # Set up LDAP Connection
    try:
        conn = ldaputils.Connection(config.LDAP.uri)
        if (simple_bind == True):
            conn.simple_bind(config.LDAP.binddn, config.LDAP.password)
        else:
            conn.gssapi_bind()
    except ldap.INVALID_CREDENTIALS:
        print "Authentication failed for server: %s" % config.LDAP.uri
        sys.exit(1)
    except ldap.NO_SUCH_OBJECT:
        print "Authentication failed for server: %s, no such object. Is your Bind DN correct?"
        sys.exit(1)
    except ldap.SERVER_DOWN:
        print "Could not contact server: %s" % config.LDAP.uri
        sys.exit(1)

    if action == "list":
        list(conn, config, service)
    elif action == "run":
        run(conn, config, service)
    else:
        usage()
        sys.exit(2)

if __name__ == "__main__":
    main()
